package cn.kgc.mes.workorder.controller;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.kgc.mes.routeprocess.domain.RouteProcess;
import cn.kgc.mes.routeproduct.domain.RouteProduct;
import cn.kgc.mes.routeproduct.service.RouteProductService;
import cn.kgc.mes.common.utils.DateUtils;
import cn.kgc.mes.storage.domain.MaterialStock;
import cn.kgc.mes.storage.service.IMaterialStockService;
import cn.kgc.mes.type.domain.MdItem;
import cn.kgc.mes.system.domain.SysMessage;
import cn.kgc.mes.system.service.ISysMessageService;
import cn.kgc.mes.workorder.domain.MdProductBom;
import cn.kgc.mes.workorder.domain.ProWorkorderBom;
import cn.kgc.mes.workorder.service.IMdProductBomService;
import cn.kgc.mes.workorder.service.ProWorkorderBomService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import cn.kgc.mes.common.annotation.Log;
import cn.kgc.mes.common.core.controller.BaseController;
import cn.kgc.mes.common.core.domain.AjaxResult;
import cn.kgc.mes.common.enums.BusinessType;
import cn.kgc.mes.workorder.domain.ProWorkorder;
import cn.kgc.mes.workorder.service.IProWorkorderService;
import cn.kgc.mes.common.utils.poi.ExcelUtil;
import cn.kgc.mes.common.core.page.TableDataInfo;

import static java.time.LocalTime.now;

/**
 * 生产工单Controller
 * 
 * @author cly
 * @date 2025-09-11
 */
@RestController
@RequestMapping("/workorder/workorder")
public class ProWorkorderController extends BaseController
{
    @Autowired
    private IProWorkorderService proWorkorderService;
    @Autowired
    private IMdProductBomService mdProductBomService;
    @Autowired
    private IMaterialStockService materialStockService;
    @Autowired
    private ProWorkorderBomService proWorkorderBomService;
    @Autowired
    private ISysMessageService sysMessageService;
    /**
     * 查询生产工单列表
     */
//    @PreAuthorize("@ss.hasPermi('workorder:workorder:list')")
    @GetMapping("/list")
    public TableDataInfo list(ProWorkorder proWorkorder)
    {
        startPage();
        List<ProWorkorder> list = proWorkorderService.selectProWorkorderList(proWorkorder);
        return getDataTable(list);
    }

    /**
     * 查询生产排产中的工单列表
     * @param proWorkorder
     * @return
     */
    @GetMapping("/enterList")
    public TableDataInfo enterList(ProWorkorder proWorkorder)
    {
        startPage();
        List<ProWorkorder> list = proWorkorderService.selectProWorkorderList2(proWorkorder);
        return getDataTable(list);
    }


    /**
     * 查询近一周的工单
     */
    @GetMapping("/listWorkorderWeek")
    public TableDataInfo listWorkorderWeek()
    {
        // 获取一周前的日期，并设置时间为当天的0点0分0秒
        LocalDateTime startDateTime = LocalDateTime.now().minusWeeks(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
        LocalDateTime endDateTime = LocalDateTime.now();
        // 转换为Timestamp或使用DateTimeFormatter
        Timestamp startTime = Timestamp.valueOf(startDateTime);
        Timestamp endTime = Timestamp.valueOf(endDateTime);
        LambdaQueryWrapper<ProWorkorder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ge(ProWorkorder::getCreateTime, startTime)
                .select(ProWorkorder::getWorkorderId, ProWorkorder::getWorkorderCode, ProWorkorder::getWorkorderName,ProWorkorder:: getProductName,
                        ProWorkorder::getProductSpc,ProWorkorder::getQuantity, ProWorkorder::getQuantityProduced, ProWorkorder::getQuantityChanged,
                        ProWorkorder::getQuantityScheduled, ProWorkorder::getRequestDate,
                        ProWorkorder::getFinishDate, ProWorkorder::getStatus,
                        ProWorkorder::getCreateTime)
                .le(ProWorkorder::getCreateTime, endTime)
                .orderByDesc(ProWorkorder::getCreateTime);
        List<ProWorkorder> list = proWorkorderService.list(queryWrapper);
        return getDataTable(list);
    }

    /**
     *  获取近一周的每天的日期和工单数
     */
    @GetMapping("/WorkorderWeekAndNum")
    public TableDataInfo WorkorderWeekAndNum() {
        List<ProWorkorder> list = proWorkorderService.selectWorkorderWeekAndNum();
        return getDataTable(list);
    }


    /**
     * 导出生产工单列表
     */
//    @PreAuthorize("@ss.hasPermi('workorder:workorder:export')")
    @Log(title = "生产工单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ProWorkorder proWorkorder)
    {
        List<ProWorkorder> list = proWorkorderService.selectProWorkorderList(proWorkorder);
        ExcelUtil<ProWorkorder> util = new ExcelUtil<ProWorkorder>(ProWorkorder.class);
        util.exportExcel(response, list, "生产工单数据");
    }

    /**
     * 获取生产工单详细信息
     */
//    @PreAuthorize("@ss.hasPermi('workorder:workorder:query')")
    @GetMapping(value = "/{workorderId}")
    public AjaxResult getInfo(@PathVariable("workorderId") Long workorderId)
    {
        return success(proWorkorderService.selectProWorkorderByWorkorderId(workorderId));
    }

    /**
     * 新增生产工单
     */
//    @PreAuthorize("@ss.hasPermi('workorder:workorder:add')")
    @Log(title = "生产工单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ProWorkorder proWorkorder)
    {
        int i = proWorkorderService.insertProWorkorder(proWorkorder);
        return AjaxResult.success(i);
    }

    /**
     * 修改生产工单
     */
//    @PreAuthorize("@ss.hasPermi('workorder:workorder:edit')")
    @Log(title = "生产工单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ProWorkorder proWorkorder)
    {
        return toAjax(proWorkorderService.updateProWorkorder(proWorkorder));
    }

    /**
     * 删除生产工单
     */
//    @PreAuthorize("@ss.hasPermi('workorder:workorder:remove')")
    @Log(title = "生产工单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{workorderIds}")
    public AjaxResult remove(@PathVariable Long[] workorderIds)
    {
        return toAjax(proWorkorderService.deleteProWorkorderByWorkorderIds(workorderIds));
    }

    //根据产品ID查询BOM组成表
    @GetMapping("/getBomById")
    public TableDataInfo getBomById(@RequestParam Integer productId){
        LambdaQueryWrapper<MdProductBom> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MdProductBom::getItemId, productId);
        List<MdProductBom> list = mdProductBomService.list(queryWrapper);
        for (int i = 0; i < list.size(); i++) {
            LambdaQueryWrapper<MaterialStock> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(MaterialStock::getItemId, list.get(i).getBomItemId())
                    .select(MaterialStock::getQuantityOnhand);
            MaterialStock materialStock = materialStockService.getOne(queryWrapper1);
            list.get(i).setQuantityOnhand(materialStock.getQuantityOnhand());
        }
        return getDataTable(list);
    }
    /**
     * 优化上面这个方法
     */
    @GetMapping("/getBomById2")
    public TableDataInfo getBomById2(@RequestParam Integer productId){
        List<MdProductBom> list = mdProductBomService.selectBomById(productId);
        return getDataTable(list);
    }

    /**
     * 生产工单BOM组成表 批量插入
     */
    @PostMapping("/addWorkorderBom")
    public AjaxResult addWorkorderBom(@RequestBody List<ProWorkorderBom> list){
        boolean result = proWorkorderBomService.saveBatch(list);
        return toAjax(result);
    }


    /**
     * 根据工单编码获取当前工单的BOM组成
     */
    @GetMapping("/getWorkInnerBomList")
    public TableDataInfo getWorkInnerBomList(@RequestParam String workorderCode){
        LambdaQueryWrapper<ProWorkorderBom> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProWorkorderBom::getWorkorderId, workorderCode)
                .select(ProWorkorderBom::getLineId, ProWorkorderBom::getWorkorderId, ProWorkorderBom::getItemId,
                        ProWorkorderBom::getItemCode,ProWorkorderBom::getItemName, ProWorkorderBom::getItemSpc,
                        ProWorkorderBom::getUnitOfMeasure, ProWorkorderBom::getItemOrProduct, ProWorkorderBom::getQuantity,
                        ProWorkorderBom::getRemark, ProWorkorderBom::getCreateTime);
        List<ProWorkorderBom> list = proWorkorderBomService.list(queryWrapper);
        return getDataTable(list);
    }
//根据当前产品编码取出工艺过程集合
    @GetMapping("/getRouteId")
    public Object getRouteId(@RequestParam String productCode){
        List<RouteProcess> list = proWorkorderService.getWorkList(productCode);
        Map<String, Object> map=new HashMap<>();
        if(list!=null){
            map.put("code",200);
            map.put("msg","查询成功");
            map.put("data",list);
        }else{
            map.put("code",0);
            map.put("msg","查询失败");
        }
        return map;
    }
    //修改工单的是否已添加排产任务
    @PostMapping("/updataWorkerTask")
    public Object updateWorkorder(@RequestParam("workorderCode") String workorderCode){
        System.out.println(workorderCode);
        UpdateWrapper<ProWorkorder> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("workorder_code", workorderCode).set("task",'Y');
        boolean result = proWorkorderService.update(updateWrapper);
        return result ? "修改成功" : "修改失败";
    }



    /**
     * 添加补货消息
     */
    @PostMapping("/addSysMessage")
    public AjaxResult addSysMessage(@RequestBody SysMessage sysMessage){
        sysMessage.setCreateTime(LocalDateTime.now());
        return toAjax(sysMessageService.save(sysMessage));
    }

}
